package com.sunshine.lnuplus.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt


/**
 * Created by sunshine on 2020/3/16
 * 参考了
 * https://www.jianshu.com/p/e689d3247b72
 */

class ArcView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr){

    private var paint: Paint = Paint()
    private var mStartPoint: PointF
    private var mEndPoint: PointF
    private var mControlPoint: PointF
    private var mWidth = 0
    private var mHeight = 0
    private val mPath: Path = Path()
    private val mArcHeight = 100 // 圆弧高度
    private var mStartColor = 0
    private var mEndColor = 0
    private var mLinearGradient: LinearGradient? = null

    init {
        paint.apply {
            isAntiAlias = true
            strokeWidth = 10f
            style = Paint.Style.FILL
        }

        mStartPoint = PointF(0f, 0f)
        mEndPoint = PointF(0f, 0f)
        mControlPoint = PointF(0f, 0f)

        mStartColor = Color.parseColor("#FF3A80")
        mEndColor = Color.parseColor("#FF3745")
    }

    fun setColor(@ColorInt startColor: Int, @ColorInt endColor: Int) {
        mStartColor = startColor
        mEndColor = endColor
        mLinearGradient = LinearGradient(
            mWidth / 2f,
            0f,
            mWidth / 2f,
            mHeight.toFloat(),
            mStartColor,
            mEndColor,
            Shader.TileMode.MIRROR
        )
        invalidate()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)


        mWidth = w
        mHeight = h

        mPath.reset()

        mPath.moveTo(0f, 0f)
        mPath.addRect(0f, 0f, mWidth.toFloat(), mHeight - mArcHeight.toFloat(), Path.Direction.CCW)

        mStartPoint.x = 0f
        mStartPoint.y = mHeight - mArcHeight.toFloat()

        mEndPoint.x = mWidth.toFloat()
        mEndPoint.y = mHeight - mArcHeight.toFloat()

        mControlPoint.x = mWidth / 2 - 50.toFloat()
        mControlPoint.y = mHeight + 100.toFloat()

        // 初始化shader
        mLinearGradient = LinearGradient(
            mWidth / 2f,
            0f,
            mWidth / 2f,
            mHeight.toFloat(),
            mStartColor,
            mEndColor,
            Shader.TileMode.MIRROR
        )

        ///SweepGradient sweepGradient = new SweepGradient(mEndPoint.x / 2,mEndPoint.y / 2,mStartColor,mEndColor);
        //paint.setShader(sweepGradient);
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        paint.shader = mLinearGradient
        mPath.moveTo(mStartPoint.x, mStartPoint.y)
        mPath.quadTo(mControlPoint.x, mControlPoint.y, mEndPoint.x, mEndPoint.y)
        canvas.drawPath(mPath, paint)
    }
}